package ru.gr.alphaversion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class GetJSON {
	//Context mContext;
	
	//public GetJSON(Context mContext) {
	//	this.mContext = mContext;
	//}
	
	public String postData(String ItemId, String ItemName, String func, String quantity, Context context) throws JSONException {
		
		//ProgressDialog dialog = new ProgressDialog(context);
		//dialog.setMessage("Wait");
		//dialog.show();
		
		//Create a new HttpClient and Post Header
	
        String text = "";
        //if(hasInternetConnection()){
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://giperbaza.ru/droid/list.php");      
        JSONObject json = new JSONObject();
        JSONObject blbla = new JSONObject();
        
        try {
            // JSON data:           
        	
        	
            if (func.equals("QSearchItemById") || func.equals("QDelItem")) {
            	blbla.put("id", ItemId);
            }
            
            if (func.equals("QGetParent")) {
            	blbla.put("id", ItemId);
            }
            
            if (func.equals("QGetQua")) {
            	blbla.put("id", ItemId);
            }
            
            if (func.equals("QSearchItemByName")) {
            	blbla.put("name", ItemName);
            }
            
            if (func.equals("QDelList")) {
            	blbla.put("listid", ItemId);
            }
            
            if (func.equals("QAddNameList")) {
            	blbla.put("cname", ItemName);
            	blbla.put("mid", ItemId);
            }
            
            if (func.equals("QOrderList")) {
            	blbla.put("listid", ItemId);
            	blbla.put("mid", ItemName);
            }
            
            if (func.equals("QGetList")) {
            	blbla.put("listid", ItemId);
            	
            }
            
            if (func.equals("QGetLists")) {
            	blbla.put("listid", "");
            }
            
            if (func.equals("QCatalog")) {
            	blbla.put("id", ItemId);
            }
            
            if (func.equals("QLogin")) {
            	blbla.put("lg", ItemName);
            	blbla.put("pw", quantity);
            }
            
            if (func.equals("QAddItem")) {
            	blbla.put("itemid", ItemId); 
            	blbla.put("qua", quantity);
            	blbla.put("listid", Main.list_id);
            }
            
            if (func.equals("QEditItem")) {
            	blbla.put("id", ItemId);
            	blbla.put("qua", quantity);
            }
            
            if (!func.equals("QAddList")) {
            	json.put("param", blbla);
            }
            json.put("func", func);
           // String bb = "/{"func":"QSearchItemById","param":{"id",ItemId}}\"; 
            JSONArray postjson=new JSONArray();
            postjson.put(json);
            // Post the data:
            httppost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
            StringEntity se = new StringEntity("json= "+URLEncoder.encode(json.toString(), "utf-8")); 
            httppost.setEntity(se);
            
            		/*HttpParams httpParameters = new BasicHttpParams();
            		// Set the timeout in milliseconds until a connection is established.
            		int timeoutConnection = 3000;
            		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            		// Set the default socket timeout (SO_TIMEOUT) 
            		// in milliseconds which is the timeout for waiting for data.
            		int timeoutSocket = 3000;
            		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            		BasicHttpResponse httpResponse = (BasicHttpResponse)  httpClient.execute(httppost);*/
            

            // Execute HTTP Post Request
           //System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);
            // for JSON:
            if(response != null)
            {
                InputStream is = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                text = sb.toString();
            }

        } catch (Exception e) {
        	//Toast.makeText(context, "Нет ответа от сервера", Toast.LENGTH_LONG).show();
        	//dialog.dismiss();
        	new AlertDialog.Builder(context)
            .setTitle("Ошибка")
            .setMessage("Нет ответа от сервера")
            .setPositiveButton(android.R.string.yes, null).create().show();
            // TODO Auto-generated catch block
        }/* catch (IOException e) {
            // TODO Auto-generated catch block
        } catch (ClientProtocolException e) {
        	
        }*/
        //dialog.dismiss();
       
   // }
	//else
	//{
	//	Toast.makeText(mContext, "Нет соединения", Toast.LENGTH_LONG).show();
	//}
        return text;
	}
	
	/*public boolean hasInternetConnection() {
	     ConnectivityManager cm =        (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	     if (cm == null) {
	      return false;
	     }
	     NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	     if (netInfo == null) {
	      return false;
	     }
	     for (NetworkInfo ni : netInfo)
	     {
	         if (ni.getTypeName().equalsIgnoreCase("WIFI"))
	             if (ni.isConnected()) {
	                 Log.d(this.toString(), "test: wifi conncetion found");
	     return true	;
	             }
	         if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
	             if (ni.isConnected()) {
	                 Log.d(this.toString(), "test: mobile connection found");
	     return true;
	             }
	     }
	  return false;
	 }*/
	
/*	public String DescJSON() {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(
				"http://twitter.com/statuses/user_timeline/vogella.json");
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(GetJSON.class.toString(), "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}*/
}